package com.neudu.yiyang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neudu.yiyang.mapper.BedMapper;
import com.neudu.yiyang.mapper.CustomerMapper;
import com.neudu.yiyang.pojo.Bed;
import com.neudu.yiyang.pojo.Beddetails;
import com.neudu.yiyang.pojo.Customer;
import com.neudu.yiyang.service.BeddetailsService;
import com.neudu.yiyang.mapper.BeddetailsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author 16462
* @description 针对表【beddetails】的数据库操作Service实现
* @createDate 2025-03-31 21:56:23
*/
@Service
public class BeddetailsServiceImpl extends ServiceImpl<BeddetailsMapper, Beddetails>
        implements BeddetailsService{
    @Autowired
    private BeddetailsMapper beddetailsMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private BedMapper bedMapper;

    @Override
    public List<Beddetails> list(String keyword) {
        if (keyword != null &&!keyword.trim().isEmpty()) {
            return beddetailsMapper.selectByKeyword(keyword);
        } else {
            return beddetailsMapper.selectAll();
        }
    }

    @Override
    public Beddetails getByIdWithCustomer(Integer id) {
        Beddetails beddetails = beddetailsMapper.selectById(id);
        if (beddetails != null && beddetails.getCustomerId() != null) {
            // 查询关联的 customer 对象
            Customer customer = customerMapper.selectById(beddetails.getCustomerId());
            beddetails.setCustomer(customer); // 设置 customer 对象
        }
        return beddetails;
    }

    // 新增床位详情（同时更新顾客和床位状态）
    @Override
    @Transactional
    public boolean save(Beddetails beddetails) {
        // 检查床位是否可用
        Bed bed = bedMapper.selectById(beddetails.getBedId());
        System.out.println("床位状态：" + (bed == null ? "不存在" : "状态：" + bed.getBedStatus()));

        // 检查顾客是否已分配床位
        Customer customer = customerMapper.selectById(beddetails.getCustomerId());
        System.out.println("顾客当前 bedId：" + customer.getBedId());

        if (bed == null || bed.getBedStatus() != 1) {
            System.out.println("床位不可用或已被占用");
            return false;
        }

        if (customer.getBedId() != null) {
            System.out.println("顾客已分配床位，ID：" + customer.getId());
            return false;
        }

        try {
            // 传入 bedId 和 customerId
            bedMapper.updateBedStatus(beddetails.getBedId(), beddetails.getCustomerId());
            customerMapper.updateBedId(customer.getId(), beddetails.getBedId());
            baseMapper.insert(beddetails);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("事务处理出现异常: " + e.getMessage());
            // 回滚事务
            return false;
        }
    }



}


